package com.gin;

import org.apache.spark.SparkConf;
import org.apache.spark.SparkContext;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.FlatMapFunction;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.api.java.function.PairFunction;
import org.apache.spark.api.java.function.VoidFunction;
import scala.Tuple2;

import java.util.Arrays;
import java.util.Iterator;

public class WordCountJava {
    public static void main(String[] args) {
        //通用配置
        //spark 配置类
        SparkConf conf = new SparkConf();
        //任务名称(必须)
        conf.setAppName("wordCountJava");
        //local: 单机本地运行
        conf.setMaster("local");

        //spark上下文对象,加载配置
        JavaSparkContext sc = new JavaSparkContext(conf);


        //具体数据处理应用程序
        //单词统计
        //默认按照换行符进行每行切割
        JavaRDD<String> fileRDD = sc.textFile("scala/data/wordCount.txt");
        //数据扁平化处理, 按空格对每行数据进行切割(hello world)
        //fileRDD.flatMap((FlatMapFunction<String, String>) s -> Arrays.asList(s.split(" ")).iterator());
        JavaRDD<String> words = fileRDD.flatMap(new FlatMapFunction<String, String>() {
            @Override
            public Iterator<String> call(String s) throws Exception {
                return Arrays.asList(s.split(" ")).iterator();
            }
        });
        //数据映射, 单个元素映射为利于统计的二元组
        // hello -> (hello,1)
        // world -> (world,1)
        JavaPairRDD<String, Integer> pairWord = words.mapToPair(new PairFunction<String, String, Integer>() {

            @Override
            public Tuple2<String, Integer> call(String s) throws Exception {
                return new Tuple2<>(s, 1);
            }
        });

        //利用二元组进行统计(x:oldValue  y:currentValue)
        JavaPairRDD<String, Integer> res = pairWord.reduceByKey(new Function2<Integer, Integer, Integer>() {
            @Override
            public Integer call(Integer old, Integer current) throws Exception {
                return old + current;
            }
        });
        //必须要有输入时,RDD才会真正执行
        res.foreach(new VoidFunction<Tuple2<String, Integer>>() {
            @Override
            public void call(Tuple2<String, Integer> val) throws Exception {
                System.out.println(val);
            }
        });

    }
}
